
from django.shortcuts import render
from rest_framework.views import APIView
import re
from rest_framework.response import Response
from .models import User
# Create your views here.
class Register(APIView):
    def post(self,request):
        user = request.data.get('admin')
        pwd = request.data.get('pass')
        checkpwd = request.data.get('checkpass')
        phone = request.data.get('tel')
        if not re.findall(r"^1[3-9]\d{9}$", phone):
            return Response({'code': 204, "msg": '手机号不合法'})
        if not pwd == checkpwd:
            return Response({'code':204,'msg':'两次密码不一致'})
        if not all([user, pwd, checkpwd, phone]):
            return Response({'code': 204, 'msg': '用户信息不完整'})
            # 3.创建用户对象，并存储
        User.objects.create_user(username=user,password=pwd, mobile=phone)
        return Response({'code': 200, 'msg': '注册成功'})
import random
# from users.utils import send_message
from users.tasks import send_message
import redis
import json
#发送验证码
class SmsCodeView(APIView):
    def post(self,request):
        #1.接收前端数据
        mobile = request.data.get('mobile')
        uuid = request.data.get('uuid')

        # 2 .生成随机验证码
        sms_code = random.randint(1000,99999)
        expire = 10
        # 3 .给容联云发送请求 提交异步任务到celery队列
        result = send_message.delay(sms_code,mobile, expire)

        # 4 .判断是否发送成功
        # if result:
        #     #成功发送，存储sms_code---->redis
        #     sms_key = "sms_%s"%uuid
        #     redis_cli = redis.Redis()
        #     redis_cli.set(sms_key,sms_code)
        #     return Response({'code':200,'msg':'短信发送成功'})
        # else:
        #     return Response({'code':400,'msg':'短信发送失败'})
        redis_cli = redis.Redis()
        sms_key = "sms_%s"%uuid
        redis_cli.set(sms_key,sms_code)
        return Response({'code':200,'msg':'短信已发送，请注意查收'})
#登录
from django.contrib.auth.hashers import check_password
from rest_framework_jwt.utils import jwt_payload_handler,jwt_encode_handler
class LoginCountView(APIView):
    def post(self,request):
        # 1 .d接收前端数据
        mobile = request.data.get('mobile')
        sms_code = request.data.get('code')
        username = request.data.get('username')
        password = request.data.get('password')
        uuid_ = request.data.get('uuid')
        # 2 .判断用户是否第一次登录
        user = User.objects.filter(username=username).first()
        redis_cli = redis.Redis()
        sms_key = 'sms_%s'%uuid_
            #是第一次登录
        if not user:
            stored_sms_code = redis_cli.get(sms_key)
            if stored_sms_code:
                if stored_sms_code.decode() == sms_code:
                        #用户输入的验证码认证通过
                    User.objects.create_user(username=username,
                                                 password=password,
                                                mobile=mobile)
                    return Response({'code':'201','msg':'注册成功，需申请管理员权限'})
                return Response({'code':'204','msg':'验证码过期或者错误'})
        # 不是第一次登录
        else:
           #优先使用用户名&密码的方式来登录
            if check_password(password,user.password):
                #认证用户通过，检查是否有权限
                if user.is_active and user.is_staff:
                    token = self.gen_token(user)
                    #获取用户所有的角色，
                    # roles = user.role.all()
                    # # 根据角色获取所有的权限,整体汇总
                    # temp = []
                    # for role in roles:
                    #     #获取当前角色的所有权限
                    #     permissions = role.permission_set.all().values_list("code_name")
                    #     permissions_list = [i[0] for i in permissions]
                    #     #权限追加
                    #     temp += permissions_list
                    # #权限去重
                    # user_permissions_list = list(set(temp))
                    # #存储权限到redis
                    # #格式如：user_permissions_uid :'["get ^user/permission/$",....]'
                    # key = "user_permissions_%s"%user.id
                    # redis_cli.set(key,json.dumps(user_permissions_list))
                    # #最终返回响应
                    return Response({
                        "code":'200',
                        'msg':'登录成功，进入首页',
                        'token':token,
                        'user':user.username
                    })
                #认证通过，但是还没有管理员权限
                return Response({'code':"206",'msg':'没有管理员权限'})
            else:
                #密码校验错误，使用短信验证码 来验证当前用户，并重置密码
                stored_sms_code = redis_cli.get(sms_key)
                if stored_sms_code:
                    if stored_sms_code.decode() == sms_code:
                        # 用户输入的验证码认证通过，则重置密码
                        user.set_password(password)
                        user.save()
                        return Response({'code': '207', 'msg': '密码已重置'})
                return Response({'code': '204', 'msg': '验证码过期或者错误'})


    @staticmethod
    def gen_token(user):
        """

        :param user: 当前登录的用户对象
        :return: jwt token
        """
        #使用用户对象，生成payload数据
        payload = jwt_payload_handler(user)
        print('生成的payload数据：',payload)
        #编码生成toeken
        token = jwt_encode_handler(payload)
        print(".....",token)
        return token

#统计用户总数
class UserCountView(APIView):
    def get(self,request):
        #当前用户总数
        num = User.objects.all().count()
        return Response({'code':'200','msg':'获取用户总数成功','total_count':num})

#统计日增用户总数
import time
class DailyAddUserView(APIView):
    def get(self,request):
        date = time.strftime("%Y-%m-%d")
        num = User.objects.filter(date_joined__contains=date).count()

        return Response({'code':'200','msg':'日增用户总数','total_count':num})

#统计日活跃用户总数
class DailyActiveUserView(APIView):
    def get(self,request):
        date = time.strftime("%Y-%m-%d")
        num = User.objects.filter(last_login__contains = date)
        return Response({'code': '200', 'msg': '日活跃用户总数', 'total_count': num})


#用户信息的视图集
from rest_framework.viewsets import ModelViewSet
from .serializers import UserSer
from rest_framework.pagination import PageNumberPagination
#定义分页类
class MyPagination(PageNumberPagination):
    #默认每页显示的条数
    page_size = 5
    #每页最大显示的条数
    max_page_size = 10
    #根据查询字符串的关键字参数
    #页码
    page_query_param = 'page'
    #每页展示多少条数据
    page_size_query_param = 'pagesize'
class UserInfoViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer

    pagination_class = MyPagination

    def create(self, request, *args, **kwargs):
        print("新增用户的信息：",request.data)
        #实例序列化器的对象
        ser = self.get_serializer(data=request.data)
        #验证用户信息是否满足要求
        if ser.is_valid():
            #保存数据
            ser.save()
            return Response({'code':200,'msg':'添加用户成功','user':ser.data})
        else:
            return Response({'code':400,'msg':'用户信息不符合要求'})


#权限的视图集
from .models import *
from .serializers import *
class PermissionViewSet(ModelViewSet):
    queryset = Permission.objects.all()
    serializer_class = PermissionSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

#权限类型的视图集
class PermissionTypeViewSet(ModelViewSet):
    queryset = PermissionType.objects.all()
    serializer_class = PermissionTypeSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
